package com.ycsj.goldmedalnewconcept.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import com.squareup.picasso.Picasso;
import com.ycsj.goldmedalnewconcept.adapter.EvaluationAdapter;
import com.ycsj.goldmedalnewconcept.bean.QuanziResponse;
import com.ycsj.goldmedalnewconcept.bean.QuanziResponse.CircleInfo;
import com.ycsj.goldmedalnewconcept.bean.QuanziResponse.Friendlist;
import com.ycsj.goldmedalnewconcept.constant.Constant;
import com.ycsj.goldmedalnewconcept.utils.SPUtil;
import com.ycsj.goldmedalnewconcept.view.PullToRefreshLayout;
import com.ycsj.goldmedalnewconcept.view.RoundImageView;
import com.ycsj.goldmedalnewconcept.R;

//我的圈子
@SuppressLint("HandlerLeak")
public class MyQuanziActivity extends Activity implements OnRefreshListener,
		OnClickListener {
	private LinearLayout llLoading;
	private ListView lv_friends;
	private EvaluationAdapter mAdapter;
	private ImageView iv_back;
	private ImageView iv_bg;
	private TextView tv_newquanzi;
	private TextView tv_name;
	private RoundImageView mImageView;
	private PullToRefreshLayout refreshLayout;
	private String friendlist = "";
	private List<CircleInfo> list;
	private List<CircleInfo> list2;
	private List<Friendlist> list1;
	private String role;
	private String account;
	private String circle_bgimg;
	private String update_date = "0";
	private int page = 0;
	private TextView loadTextView;
	private TextView tv_empty;
	private View footerView;
	private View loading;
	private boolean isLoading = false;
	private RotateAnimation loadingAnimation;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_myquanzi);

		friendlist = SPUtil.getString(getBaseContext(), "friendlistjson", "");
		role = SPUtil.getString(this, "role", "");
		account = SPUtil.getString(this, "account", "");

		list = new ArrayList<CircleInfo>();
		list2 = new ArrayList<CircleInfo>();

		loadingAnimation = (RotateAnimation) AnimationUtils.loadAnimation(this,
				R.anim.rotating);
		// 添加匀速转动动画
		LinearInterpolator lir = new LinearInterpolator();
		loadingAnimation.setInterpolator(lir);

		initView();
		setOnListener();
		initData();

	}

	Handler mhandler = new Handler() {
		public void handleMessage(Message msg) {

			switch (msg.what) {
			case 0:
				String rowid = msg.obj.toString();
				// 点赞
				OkHttpClient mOkHttpClient = new OkHttpClient();
				FormEncodingBuilder builder = new FormEncodingBuilder();
				builder = new FormEncodingBuilder();
				builder.add("type", "3");
				builder.add("cirlerowid", rowid);
				builder.add("c", account);
				builder.add("role", role);
				builder.add("status", "0");
				Request request = new Request.Builder()
						.url(Constant.SERVER_LOC + "CircleMsg")
						.post(builder.build()).build();
				mOkHttpClient.newCall(request).enqueue(
						new com.squareup.okhttp.Callback() {
							// http://192.168.0.198:8888/ycsj_platform/CircleMsg?type=3&cirlerowid=55&c=18672626702&role=3&status=0
							public void onFailure(Request arg0, IOException arg1) {

							}

							public void onResponse(Response arg0)
									throws IOException {

								Gson gson = new Gson();
								String json = arg0.body().string();
								Log.e("test", json);
								// Toast.makeText(MyQuanziActivity.this, "赞+1",
								// Toast.LENGTH_SHORT).show();

							}
						});
				break;
			case 1:// 评论
				List<String> list = new ArrayList<String>();
				list = (List<String>) msg.obj;

				String crowid = list.get(0);
				String c2 = list.get(1);
				String role2 = list.get(2);
				String content = list.get(3);

				OkHttpClient mOkHttpClient1 = new OkHttpClient();
				FormEncodingBuilder builder1 = new FormEncodingBuilder();
				builder1.add("type", "6");
				builder1.add("cirlerowid", crowid);
				builder1.add("c", account);
				builder1.add("role", role);
				builder1.add("font", "");
				builder1.add("content", content);
				builder1.add("status", "0");
				Request request1 = new Request.Builder()
						.url(Constant.SERVER_LOC + "CircleMsg")
						.post(builder1.build()).build();
				mOkHttpClient1.newCall(request1).enqueue(
						new com.squareup.okhttp.Callback() {
							// http://192.168.0.198:8888/ycsj_platform/CircleMsg?type=3&cirlerowid=55&c=18672626702&role=3&status=0

							public void onFailure(Request arg0, IOException arg1) {

							}

							public void onResponse(Response arg0)
									throws IOException {

								Gson gson = new Gson();
								String json = arg0.body().string();
								Log.e("test", json);

								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										Toast.makeText(MyQuanziActivity.this,
												"评论成功", Toast.LENGTH_SHORT)
												.show();
										onRefresh();
									}
								});
							}
						});

				break;
			case 2:// 删除圈子消息
				String delrowid = msg.obj.toString();

				OkHttpClient mOkHttpClient2 = new OkHttpClient();
				FormEncodingBuilder builder2 = new FormEncodingBuilder();
				builder2.add("type", "13");
				builder2.add("rowid", delrowid);
				builder2.add("c", account);
				builder2.add("role", role);
				builder2.add("status", "-1");
				Request request2 = new Request.Builder()
						.url(Constant.SERVER_LOC + "CircleMsg")
						.post(builder2.build()).build();
				mOkHttpClient2.newCall(request2).enqueue(
						new com.squareup.okhttp.Callback() {
							// http://192.168.0.198:8888/ycsj_platform/CircleMsg?type=3&cirlerowid=55&c=18672626702&role=3&status=0
							public void onFailure(Request arg0, IOException arg1) {

							}

							public void onResponse(Response arg0)
									throws IOException {

								Gson gson = new Gson();
								String json = arg0.body().string();
								Log.e("test", json);

								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										Toast.makeText(MyQuanziActivity.this,
												"删除成功", Toast.LENGTH_SHORT)
												.show();
										onRefresh();
									}
								});
							}
						});

				break;
			case 3:// 取消赞
				String qurowid = msg.obj.toString();

				OkHttpClient mOkHttpClient3 = new OkHttpClient();
				FormEncodingBuilder builder3 = new FormEncodingBuilder();
				builder3.add("type", "4");
				builder3.add("cirlerowid", qurowid);
				builder3.add("c", account);
				builder3.add("role", role);
				builder3.add("status", "-1");
				Request request3 = new Request.Builder()
						.url(Constant.SERVER_LOC + "CircleMsg")
						.post(builder3.build()).build();
				mOkHttpClient3.newCall(request3).enqueue(
						new com.squareup.okhttp.Callback() {
							// http://192.168.0.198:8888/ycsj_platform/CircleMsg?type=3&cirlerowid=55&c=18672626702&role=3&status=0
							public void onFailure(Request arg0, IOException arg1) {

							}

							public void onResponse(Response arg0)
									throws IOException {

								Gson gson = new Gson();
								String json = arg0.body().string();
								Log.e("test", json);
								// Toast.makeText(MyQuanziActivity.this, "取消赞",
								// Toast.LENGTH_SHORT).show();
							}
						});
				break;
			case 4:// 个人中心
				List<String> list5 = new ArrayList<String>();
				list5 = (List<String>) msg.obj;
				String c4 = list5.get(0);
				String role4 = list5.get(1);

				Intent intent1 = new Intent(MyQuanziActivity.this,
						UserInfoActivity.class);
				intent1.putExtra("c", c4);
				intent1.putExtra("role", role4);
				startActivity(intent1);

				break;
			case 5:// 删除评论

				List<String> list3 = new ArrayList<String>();
				list3 = (List<String>) msg.obj;

				// for (int i = 0; i < list3.size(); i++) {
				// Log.e("test", list3.get(i));
				// }

				String cirlerowid = list3.get(0);
				crowid = list3.get(1);

				OkHttpClient mOkHttpClient5 = new OkHttpClient();
				FormEncodingBuilder builder5 = new FormEncodingBuilder();
				builder5.add("type", "8");
				builder5.add("rowid", crowid);
				builder5.add("cirlerowid", cirlerowid);
				builder5.add("c", account);
				builder5.add("role", role);
				Request request5 = new Request.Builder()
						.url(Constant.SERVER_LOC + "CircleMsg")
						.post(builder5.build()).build();
				mOkHttpClient5.newCall(request5).enqueue(
						new com.squareup.okhttp.Callback() {
							// http://192.168.0.198:8888/ycsj_platform/CircleMsg?type=3&cirlerowid=55&c=18672626702&role=3&status=0

							public void onFailure(Request arg0, IOException arg1) {

							}

							public void onResponse(Response arg0)
									throws IOException {

								Gson gson = new Gson();
								String json = arg0.body().string();
								Log.e("test", json);

								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										Toast.makeText(MyQuanziActivity.this,
												"删除成功", Toast.LENGTH_SHORT)
												.show();
										onRefresh();
									}
								});
							}
						});

				break;
			case 6:// 回复评论
				List<String> list2 = new ArrayList<String>();
				list2 = (List<String>) msg.obj;

				crowid = list2.get(0);
				c2 = list2.get(1);
				role2 = list2.get(2);
				content = list2.get(3);

				OkHttpClient mOkHttpClient6 = new OkHttpClient();
				FormEncodingBuilder builder6 = new FormEncodingBuilder();
				builder6.add("type", "7");
				builder6.add("cirlerowid", crowid);
				builder6.add("c", account);
				builder6.add("role", role);
				builder6.add("c2", c2);
				builder6.add("role2", role2);
				builder6.add("font", "");
				builder6.add("content", content);
				builder6.add("status", "0");
				Request request6 = new Request.Builder()
						.url(Constant.SERVER_LOC + "CircleMsg")
						.post(builder6.build()).build();
				mOkHttpClient6.newCall(request6).enqueue(
						new com.squareup.okhttp.Callback() {
							// http://192.168.0.198:8888/ycsj_platform/CircleMsg?type=3&cirlerowid=55&c=18672626702&role=3&status=0

							public void onFailure(Request arg0, IOException arg1) {

							}

							public void onResponse(Response arg0)
									throws IOException {

								Gson gson = new Gson();
								String json = arg0.body().string();
								Log.e("test", json);

								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										Toast.makeText(MyQuanziActivity.this,
												"评论成功", Toast.LENGTH_SHORT)
												.show();
										onRefresh();
									}
								});
							}
						});
				break;
			case 7:// 转发
				List<String> list4 = new ArrayList<String>();
				list4 = (List<String>) msg.obj;

				crowid = list4.get(0);
				c2 = list4.get(1);
				role2 = list4.get(2);
				String nickname = list4.get(3);

				OkHttpClient mOkHttpClient7 = new OkHttpClient();
				FormEncodingBuilder builder7 = new FormEncodingBuilder();
				builder7.add("type", "14");
				builder7.add("c", account);
				builder7.add("role", role);
				builder7.add("rowid", crowid);
				builder7.add("c2", c2);
				builder7.add("role2", role2);
				builder7.add("usernickname2", nickname);
				builder7.add("flag", "1");
				builder7.add("status", "0");
				Request request7 = new Request.Builder()
						.url(Constant.SERVER_LOC + "CircleMsg")
						.post(builder7.build()).build();
				mOkHttpClient7.newCall(request7).enqueue(
						new com.squareup.okhttp.Callback() {
							// http://192.168.0.198:8888/ycsj_platform/CircleMsg?type=3&cirlerowid=55&c=18672626702&role=3&status=0

							public void onFailure(Request arg0, IOException arg1) {

							}

							public void onResponse(Response arg0)
									throws IOException {

								Gson gson = new Gson();
								String json = arg0.body().string();
								Log.e("test", json);

								runOnUiThread(new Runnable() {
									@Override
									public void run() {
										Toast.makeText(MyQuanziActivity.this,
												"转发成功", Toast.LENGTH_SHORT)
												.show();
										onRefresh();
									}
								});
							}
						});

				break;
			default:
				break;
			}
		}
	};

	private void initView() {

		llLoading = (LinearLayout) findViewById(R.id.ll_loading);
		tv_newquanzi = (TextView) findViewById(R.id.tv_newquanzi);
		lv_friends = (ListView) findViewById(R.id.lv_friends);
		iv_back = (ImageView) findViewById(R.id.iv_back);
		refreshLayout = (PullToRefreshLayout) findViewById(R.id.refresh_view);

		View headerView = LayoutInflater.from(getBaseContext()).inflate(
				R.layout.myquanzi_header, null);
		iv_bg = (ImageView) headerView.findViewById(R.id.iv_bg); // 顶部背景图
		tv_name = (TextView) headerView.findViewById(R.id.tv_name); // 顶部昵称
		mImageView = (RoundImageView) headerView.findViewById(R.id.mImageView); // 顶部头像

		lv_friends.addHeaderView(headerView);
		footerView = this.getLayoutInflater().inflate(R.layout.load_more_jpstar, null);
		loading = footerView.findViewById(R.id.loading_icon);
		loadTextView = (TextView) footerView.findViewById(R.id.loadmore_tv);
		tv_empty = (TextView) footerView.findViewById(R.id.tv_empty);
		lv_friends.addFooterView(footerView, null, false);
		footerView.setOnClickListener(this);
		mImageView.setOnClickListener(this);

	}

	private void setOnListener() {
		refreshLayout.setOnRefreshListener(this);
		iv_back.setOnClickListener(this);
		tv_newquanzi.setOnClickListener(this);
		iv_bg.setOnClickListener(this);
	}

	private void initData() {

		OkHttpClient mOkHttpClient = new OkHttpClient();
		FormEncodingBuilder builder = new FormEncodingBuilder();
		builder.add("type", "10");
		builder.add("c", account);
		builder.add("role", role);
		builder.add("friendlist", friendlist);
		builder.add("c2", account);
		builder.add("role2", role);
		builder.add("update_date", update_date);
		builder.add("page", page + "");
		Request request = new Request.Builder()
				.url(Constant.SERVER_LOC + "CircleMsg").post(builder.build())
				.build();
		mOkHttpClient.newCall(request).enqueue(new Callback() {

			@Override
			public void onFailure(Request arg0, IOException arg1) {
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						if (null != llLoading
								&& llLoading.getVisibility() != View.GONE) {
							llLoading.setVisibility(View.GONE);
						}
						Toast.makeText(getBaseContext(), "网络无响应，请检查网络连接", 0)
								.show();
					}
				});
			}

			@Override
			public void onResponse(Response arg0) throws IOException {

				try {
					// 解析Json数据，保存登录状态及身份信息
					

					Gson gson = new Gson();
					String json = arg0.body().string();
					QuanziResponse fromJson = gson.fromJson(json,
							QuanziResponse.class);

					if (fromJson != null) {
						if ("-1".equals(fromJson.state)
								|| "0".equals(fromJson.state)) {
							runOnUiThread(new Runnable() {
								@Override
								public void run() {
								
									if (null != llLoading
											&& llLoading.getVisibility() != View.GONE) {
										llLoading.setVisibility(View.GONE);
									}
									
									loading.setVisibility(loading.GONE);
									loading.clearAnimation();
									loadTextView.setText("已经是最后一条了");
									loadTextView.setClickable(false);
									isLoading = true;
									page = 0;
								}
							});
						} else if ("1".equals(fromJson.state)) {
							list2 = fromJson.circlelist;
							if (page == 0) {
								list = list2;
							} else {
								list.addAll(list2);
							}

							circle_bgimg = fromJson.circle_bgimg;
							update_date = fromJson.circlelist
									.get(fromJson.circlelist.size() - 1).update_date;
							list1 = fromJson.friendlist;
							if (fromJson != null && fromJson.friendlist != null) {
								String friendlistjson = gson
										.toJson(fromJson.friendlist);
								SPUtil.putString(MyQuanziActivity.this,
										"friendlistjson", friendlistjson);

							}

							runOnUiThread(new Runnable() {
								@Override
								public void run() {
									if (null != llLoading
											&& llLoading.getVisibility() != View.GONE) {
										llLoading.setVisibility(View.GONE);
									}
									refreshLayout
											.refreshFinish(PullToRefreshLayout.REFRESH_SUCCEED);
									mAdapter = new EvaluationAdapter(
											MyQuanziActivity.this, list,
											mhandler);
									if (page == 0) {

										lv_friends.setAdapter(mAdapter);
									} else {
										runOnUiThread(new Runnable() {
											@Override
											public void run() {
												mAdapter.notifyDataSetChanged();
											}
										});
									}
									loading.setVisibility(loading.GONE);
									loading.clearAnimation();
									if (list2.size() < 5) {
										loadTextView.setText("已经是最后一条了");
										loadTextView.setClickable(false);
										isLoading = true;
										page = 0;
									} else {
										loadTextView.setText("加载更多");
										isLoading = false;
									}

									Picasso.with(MyQuanziActivity.this)
											.load(circle_bgimg).into(iv_bg);

									Picasso.with(MyQuanziActivity.this)
											.load(SPUtil.getString(
													MyQuanziActivity.this,
													"icon", ""))
											.into(mImageView);

									tv_name.setText(SPUtil.getString(
											MyQuanziActivity.this, "name", ""));

								}
							});
						}
					}

				} catch (Exception e) {
				}
			}
		});

		// EvaluationItem item = new EvaluationItem();
		// list.add(item);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;
		case R.id.mImageView:// 顶部头像
			Intent intent5 = new Intent(MyQuanziActivity.this,
					UserInfoActivity.class);
			intent5.putExtra("c", account);
			intent5.putExtra("role", role);
			startActivity(intent5);

			break;
		case R.id.tv_newquanzi:
			Intent intent = new Intent(this, QuanziCreatActivity.class);
			startActivity(intent);
			finish();
			break;
		case R.id.loadmore_layout:
			if (!isLoading) {
				loading.setVisibility(View.VISIBLE);
				loading.startAnimation(loadingAnimation);
				loadTextView.setText("正在加载...");
				isLoading = true;
				page++;
				initData();
			}
			break;
		}
	}

	@Override
	public void onRefresh() {
		// 下拉刷新操作
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				page = 0;
				update_date = "0";
				initData();
				loadTextView.setText("加载更多");
				loading.setVisibility(View.GONE);
				isLoading = false;

			}
		}, 500);
	}

}
